import type { UserInfoFace } from "@/types/user";
import { addFile, getFile } from "./file";
class UserSql {
  chatUsers: UserInfoFace[];
  sqlUrl: string;
  constructor() {
    this.chatUsers = [];
    const rootPath = __dirname //process.cwd();
    this.sqlUrl = rootPath + "../../sql/user.json";
    const arr = getFile(this.sqlUrl);
    if (arr) {

      this.chatUsers = arr;
    }
  }
  getLength() {
    return this.chatUsers.length
  }
  updateJson() {
    const newArr = this.chatUsers.map((v) => {
      const { ws, ...arg } = v;
      return arg;
    });
    addFile(this.sqlUrl, newArr);
  }
  getUser(userId: string): UserInfoFace | undefined {
    return this.chatUsers.find((v) => v.userId == userId);
  }
  sendUserInfo(userId: string) {
    const data = this.getUser(userId);
    if (data) {
      const obj1 = {
        type: "userInfo",
        userName: data.userName,
      };
      data?.ws?.send(JSON.stringify(obj1));
    }
  }

  initLogin(path: string, ws: any): Promise<UserInfoFace> {
    return new Promise((resolve, reject) => {
      if (!path) return;
      const id = path.replace(/\//g, "");
      const userInfo = this.addUser(id, ws);
      this.sendUserInfo(id);
      resolve(userInfo);
    });
  }
  addUser(userId: string, ws: any) {
    const isSome = this.chatUsers.some((v) => v.userId == userId);
    if (!isSome) {
      const data = {
        userId,
        userName: `luren${new Date().getTime().toString()}`,
        ws,

      };
      this.chatUsers.push(data);

      this.updateJson();
      return { ...data, isNew: true };
    } else {
      const index = this.chatUsers.findIndex((v) => v.userId == userId);
      if (index !== -1) {
        this.chatUsers[index].ws = ws;
        return this.chatUsers[index];
      } else {
        return;
      }
    }
  }
  editName(userId: string, name: string, isTip = true) {
    const index = this.chatUsers.findIndex((v) => v.userId == userId);
    if (index !== -1) {
      const oldName = this.chatUsers[index].userName || "路人";
      this.chatUsers[index].userName = name;
      const obj = {
        type: "system",
        name: "系统",
        msg: "你成功改名字为>" + name,
      };
      if (isTip) {
        this.chatUsers[index]?.ws.send(JSON.stringify(obj));
      }

      this.sendUserInfo(userId);
      this.updateJson();
      return `${oldName}改名为${name}`;
    }
  }
  editSex(userId: string, sex: number) {
    const index = this.chatUsers.findIndex((v) => v.userId == userId);
    if (index !== -1) {
      this.chatUsers[index].sex = sex;
      this.updateJson();
    }
  }
}
export default UserSql;
